package com.whmskj.xjlhsc.qianYiData.job;

import com.whmskj.xjlhsc.qianYiData.service.AMonthlyAverageTonOfGauzeConsumpService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.ZoneId;

/**
 * SC-05月平均吨纱支耗电（日汇总写入）
 * 仅写入工序=细纱的数据。
 */
@Slf4j
@Component
public class AMonthlyAverageTonOfGauzeConsumpJob {

    private static final ZoneId ZONE = ZoneId.of("Asia/Shanghai");

    @Resource
    private AMonthlyAverageTonOfGauzeConsumpService service;

    // 每天 00:15 执行，写入昨天的数据（避免跨日未完整）
    @Scheduled(cron = "0 15 0 * * ?")
    public void syncYesterday() {
        LocalDate today = LocalDate.now(ZONE);
        LocalDate target = today.minusDays(1);
        syncWithRetry(target, 3); // 最多重试3次
    }
    
    // 手动触发接口（用于测试或补数据）
    public void syncForDate(LocalDate date) {
        syncWithRetry(date, 2); // 手动触发重试2次
    }
    
    private void syncWithRetry(LocalDate target, int maxRetries) {
        int affected = 0;
        int retryCount = 0;
        
        while (retryCount < maxRetries) {
            try {
                affected = service.syncForDay(target);
                log.info("AMonthlyAvgJob: attempt={}, affected={}, day={}", retryCount + 1, affected, target);
                
                // 如果成功插入数据，跳出重试循环
                if (affected > 0) {
                    break;
                }
                
                // 如果没数据且还有重试机会，等待后重试
                if (retryCount < maxRetries - 1) {
                    Thread.sleep(2000); // 等待2秒
                    retryCount++;
                } else {
                    break;
                }
            } catch (Exception e) {
                log.error("AMonthlyAvgJob: attempt={} failed for {}", retryCount + 1, target, e);
                retryCount++;
                if (retryCount < maxRetries) {
                    try {
                        Thread.sleep(2000); // 等待2秒后重试
                    } catch (InterruptedException ie) {
                        Thread.currentThread().interrupt();
                        break;
                    }
                }
            }
        }
        
        if (affected == 0) {
            log.warn("AMonthlyAvgJob: all attempts failed, no data inserted for {}", target);
        }
    }
}

